const dotenv = require('dotenv')
dotenv.config()
const createError = require('http-errors')
const express = require('express')
const path = require('node:path')
const logger = require('morgan')
const expressJWT = require('express-jwt')
const app = express()

const userRouter = require('./routes/userRouter')
const categoryRouter = require('./routes/categoryRouter')
const typeRouter = require('./routes/typeRouter')
const carRouter = require('./routes/carRouter')
const shopRouter = require('./routes/shopRouter')
const orderRouter = require('./routes/orderRouter')
const uploadRouter = require('./routes/uploadRouter')
const newsRouter = require('./routes/newsRouter')

app.use(logger('dev'))
app.use(express.json())
app.use(express.urlencoded({ extended: false }))
// app.use(express.static(path.join(__dirname, 'public')))
app.use(express.static(path.join(__dirname, 'upload')))
app.use(
  expressJWT({
    secret: process.env.secret, // 签名的密钥 或 PublicKey
    algorithms: ['HS256'],
    requestProperty: 'auth',
    credentialsRequired: false, // 对无 Token 请求不进行解析和抛出异常
  }).unless({
    path: ['/user/login', '/user/register', /^\/category/, /^\/type/, /^\/shop/, '/upload', /^\/shop/, /^\/news/], // 指定路径不经过 Token 解析
  })
)

// 用户路由
app.use('/user', userRouter)
// 分类路由
app.use('/category', categoryRouter)
// 类型路由
app.use('/type', typeRouter)
// 车路由
app.use('/car', carRouter)
// 店铺路由
app.use('/shop', shopRouter)
// 订单路由
app.use('/order', orderRouter)
// 上传图片
app.use('/upload', uploadRouter)
// 资讯路由
app.use('/news', newsRouter)

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404))
})

// error handler
app.use(function (err, req, res, next) {
  // 解析token失败
  if (err.name === 'UnauthorizedError') {
    res.status(401).send('invalid token')
  } else {
    res.locals.message = err.message
    res.locals.error = req.app.get('env') === 'development' ? err : {}
    // render the error page
    res.status(err.status || 500).send({ code: err.status || 500, msg: 'fail', data: {} })
  }
})

module.exports = app
